import sys
import traceback

from flask import Flask, request, jsonify
from code_spectra.code_spectra import WebHookProcessor
from db import database
from logger import logger
from tools.webhook import WebHook

REVIEW_APP = Flask(__name__)
LOGGER = logger.CustomLogger()

@REVIEW_APP.route('/webhook', methods=['POST'])
def webhook():
    data = request.json
    hook = WebHook(data)
    user_agent = request.headers.get('User-Agent')
    hook_name = request.headers.get('X-Gitcode-Event')
    hook.user_agent = user_agent
    hook._hook_name = hook_name
    try:
        webhook_processor = WebHookProcessor(False)
        webhook_processor.process(hook)
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        formatted = traceback.format_exception(exc_type, exc_value, exc_traceback)
        LOGGER.error(f"[{hook.pr_number}] process failed for hook: {hook}, details: {str(formatted)}")
    return jsonify({'message': 'Received'}), 200


if __name__ == '__main__':
    db_mgr = database.DatabaseManager()
    db_mgr.init_db()
    REVIEW_APP.run()
